import React, { useState, useEffect, useRef } from 'react';
import { Image } from 'antd';
import { Swiper, SwiperSlide } from 'swiper/react';
import { FreeMode, Pagination, Autoplay } from 'swiper/modules';
import 'swiper/css';
import 'swiper/css/free-mode';
import 'swiper/css/pagination';
import { getBannerApi } from '@/api/recommend';

export default function SwiperComponent() {
  const [banner, setBanners] = useState([]);
  const swiperRef = useRef(null);
  // 获取轮播图
  const getBanner = async () => {
    const { banners: bannersArr } = await getBannerApi()
    setBanners(bannersArr)
  };
  useEffect(() => {
    getBanner()
  }, []);
  // 停止自动播放
  const handleMouseEnter = () => {
    if (swiperRef.current) {
      swiperRef.current.swiper.autoplay.stop();
    }
  };
  // 开启自动播放
  const handleMouseLeave = () => {
    swiperRef.current.swiper.autoplay.start();
  };
  return (
    <Swiper
      ref={swiperRef}
      slidesPerView={3}
      spaceBetween={30}
      freeMode={true}
      autoplay={{delay: 2500, disableOnInteraction: false}}
      pagination={{clickable: true}}
      modules={[FreeMode, Pagination, Autoplay]}
    >
      {
        banner.map(item => {
          const { imageUrl, typeTitle } = item
          return (
            <SwiperSlide key={imageUrl}>
              <Image 
                src={imageUrl} title={typeTitle} preview={false} height={250} 
                onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave} 
              />
            </SwiperSlide>
          )
        })
      }
    </Swiper>
  )
}
